import { cartList, addToCart, removeGoods } from '@/api/cart'
import { Toast } from 'vant'
const CHANGE_CART_LIST = 'CHANGE_CART_LIST'

const state = {
  cartList: []
}

const getters = {
  cartListGetter(state) {
    return state.cartList
  },
  countGetter(state) {
    return state.cartList.length
  }
}

const mutations = {
  [CHANGE_CART_LIST](state, arr) {
    state.cartList = arr
  }
}

const actions = {
  changeCartList({ commit }, arr) {
    commit(CHANGE_CART_LIST, arr)
  },

  // 获取购物车列表数据
  getCartListApi({ commit }) {
    return cartList().then(res => {
      if (res.resultCode === 200) {
        commit(CHANGE_CART_LIST, res.data)
      }
    })
  },

  // 添加商品到购物车
  // eslint-disable-next-line
  addGoodsToCartApi({ commit }, params) {
    return addToCart(params).then(res => {
      if (res.resultCode === 200) {
        Toast.success('添加成功')
        return true
      }
    }).catch(err => {
      Toast.fail('请求失败')
      console.log(err)
      return false
    })
  },

  // eslint-disable-next-line
  async removeGoodsApi({ commit, dispatch }, params) {
    const res = await removeGoods(params).catch(err => {
      console.log(err)
      Toast.fail('请求失败')
    })
    if (res && res.resultCode === 200) {
      Toast.success('删除成功')
      dispatch('getCartListApi')
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}